package drds.plus.common.jdbc;

import lombok.Getter;
import lombok.Setter;

import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;

public class Parameters {
    @Setter
    @Getter
    private boolean batch = false;
    @Setter
    @Getter
    private Map<Integer, SetParameterMethodAndArgs> indexToSetParameterMethodAndArgsMap = new HashMap<Integer, SetParameterMethodAndArgs>();
    @Setter
    @Getter
    private List<Map<Integer, SetParameterMethodAndArgs>> indexToSetParameterMethodAndArgsMapList = new ArrayList<Map<Integer, SetParameterMethodAndArgs>>();
    @Setter
    @Getter
    private int batchSize = 0; // batch的数量
    @Setter
    @Getter
    private int batchIndex = 0; // 记录一下遍历过程中的index
    @Setter
    @Getter
    private AtomicInteger sequenceSize = new AtomicInteger(0); // seq列的数量

    public Parameters() {
    }

    public Parameters(Map<Integer, SetParameterMethodAndArgs> indexToSetParameterMethodAndArgsMap, boolean isBatch) {
        this.indexToSetParameterMethodAndArgsMap = indexToSetParameterMethodAndArgsMap;
        this.batch = isBatch;
        /**
         * 如果是批量  其他值为默认值
         */
    }

    public void addBatch() {
        indexToSetParameterMethodAndArgsMapList.add(this.indexToSetParameterMethodAndArgsMap);
        batchSize = indexToSetParameterMethodAndArgsMapList.size();
        this.batch = true;
        //
        indexToSetParameterMethodAndArgsMap = new HashMap<Integer, SetParameterMethodAndArgs>();
    }

    /**
     * 返回批处理的参数，如果当前非批处理，返回单条记录
     */
    public List<Map<Integer, SetParameterMethodAndArgs>> getIndexToSetParameterMethodAndArgsMapList() {
        if (isBatch()) {
            return this.indexToSetParameterMethodAndArgsMapList;
        } else {
            return Arrays.asList(indexToSetParameterMethodAndArgsMap);
        }
    }

    public Map<Integer, SetParameterMethodAndArgs> getFirstIndexToSetParameterMethodAndArgsMap() {
        if (!batch) {
            return indexToSetParameterMethodAndArgsMap;
        } else {
            return indexToSetParameterMethodAndArgsMapList.get(0);
        }
    }

    public Parameters cloneByBatchIndex(int batchIndex) {
        List<Map<Integer, SetParameterMethodAndArgs>> indexToSetParameterMethodAndArgsMapList = getIndexToSetParameterMethodAndArgsMapList();
        if (batchIndex >= indexToSetParameterMethodAndArgsMapList.size()) {
            throw new IllegalArgumentException("batchIndex is invalid");
        }

        Parameters parameters = new Parameters(indexToSetParameterMethodAndArgsMapList.get(batchIndex), isBatch());
        parameters.setBatchSize(batchSize);
        parameters.setBatchIndex(batchIndex);//唯独这个是动态值
        parameters.setSequenceSize(sequenceSize);
        return parameters;
    }


}
